package com.olah.ws.service;

import com.alibaba.fastjson.JSONObject;
import com.olah.common.entity.po.ws.dto.core.WebSocketResponse;
import com.olah.ws.entities.WebSocketClient;
import lombok.Getter;
import lombok.NoArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;

@Getter
@Component
@NoArgsConstructor
@ServerEndpoint(value = "/ws/{id}")
public class WebSocketService {

    private static final Logger log = LoggerFactory.getLogger(WebSocketService.class);

    private static final ConcurrentHashMap<Integer, WebSocketClient> webSocketMap = new ConcurrentHashMap<>();

    private int id;

    @OnOpen
    public void onOpen(Session session, @PathParam("id") int id) {
        this.id = id;
        WebSocketClient client = new WebSocketClient(session);
        webSocketMap.put(id, client);
    }

    @OnClose
    public void onClose() {
        webSocketMap.remove(id);
    }
    
    public static void notifyTip(int userId, String msg) {
        WebSocketResponse response = WebSocketResponse.tip(msg);
        sendMessage(userId, response);
    }

    public static void notifySystemMsg(int userId, String msg, Object data, String handler) {
        WebSocketResponse response = WebSocketResponse.system(JSONObject.toJSONString(data), msg, handler);
        sendMessage(userId, response);
    }

    public static void notifyPrivateMsg(int userId, String msg, Object data, String handler) {
        WebSocketResponse response = WebSocketResponse._private(JSONObject.toJSONString(data), msg, handler);
        sendMessage(userId, response);
    }

    public static void sendMessage(int userId, WebSocketResponse resp) {
        try {
            WebSocketClient webSocketClient = webSocketMap.get(userId);
            if(webSocketClient != null){
                webSocketClient.getSession().getBasicRemote().sendText(resp.toString());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static int size() {
        return webSocketMap.size();
    }

    public static boolean online(Integer userId) {
        return webSocketMap.containsKey(userId);
    }

}